package ofpof.service;

import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import ofpof.domain.Session;
import ofpof.domain.User;
import ofpof.domain.dao.SessionDao;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SessionService {
	
	public static final String OFPOFID = "ofpofid";
	
	@Autowired
	private CookieHelper cookieHelper;
	
	@Autowired
	private SessionDao sessionDao;

	public void createSessionFor(User foundUser, HttpServletResponse response) {
		Session session = new Session();
		session.setUser(foundUser);
		sessionDao.create(session);
		cookieHelper.createSessionCookie(response, OFPOFID, session.getId().toString());
	}

	public void deleteSessionById(String sessionIdAsStr) {
		ObjectId sessionId = new ObjectId(sessionIdAsStr);
		sessionDao.deleteById(sessionId);
	}

	public Session updateSessionIfExists(String sessionIdAsStr) {
		ObjectId sessionId = new ObjectId(sessionIdAsStr);
		Session foundSession = sessionDao.findById(sessionId);
		if (foundSession != null) {
			foundSession.setCreatedOn(new Date());
			sessionDao.update(foundSession);
		}
		return foundSession;
	}

}
